package com.runa.monitor.platinterface.extend.nb.vo.buildmeter;

import com.runa.protocol.util.UtilTime;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.runa.protocol.util.ByteUtil.*;
import static com.runa.rccprotocol.analysis.RunaDeviceAnalysis.*;

public class BuildMeterDecode {

    public List<MqttBuildMeterDataVo> heatMeterDecode(String hexStr) {
        boolean contains = hexStr.contains("end.");
        if (contains) {
            hexStr = hexStr.replace("end.", "");
        }
        byte[] bytes = hexStringToByte(hexStr);
        int len = bytes.length;
        List<MqttBuildMeterDataVo> meters = new ArrayList<>();
        MqttBuildMeterDataVo meter;
        int idx = 0;
        while (len > 0) {
            meter = new MqttBuildMeterDataVo();
            meter.setReadDate(new Date());
            if (contains) {
                idx += 9;
            } else {
                idx += 10;
            }
            String addr = byteToHexStringFlip(bytes, idx, 4);
            meter.setSerial(addr);
            idx += 12;
            float accCold = (float) (Integer.parseInt(byteToHexStringFlip(bytes, idx, 4)) * 0.01);
            idx += 4;
            meter.setAccCold(toKwh(accCold, bytes[idx++] & 0xff));
            float accHeat = (float) (Integer.parseInt(byteToHexStringFlip(bytes, idx, 4)) * 0.01);
            idx += 4;
            meter.setAccHeat(toKwh(accHeat, bytes[idx++] & 0xff));
            float power = (float) (Integer.parseInt(byteToHexStringFlip(bytes, idx, 4)) * 0.01);
            idx += 4;
            meter.setHeat(toKw(power, bytes[idx++] & 0xff));
            float flow = (float) (Integer.parseInt(byteToHexStringFlip(bytes, idx, 4)) * 0.0001);
            idx += 4;
            meter.setFlow(toM3h(flow, bytes[idx++]));
            float accFlow = (float) (Integer.parseInt(byteToHexStringFlip(bytes, idx, 4)) * 0.01);
            idx += 4;
            meter.setAccFlow(toM3(accFlow, bytes[idx++]));
            meter.setInTemperature((float) (Integer.parseInt(byteToHexStringFlip(bytes, idx, 3)) * 0.01));
            idx += 3;
            meter.setOutTemperature((float) (Integer.parseInt(byteToHexStringFlip(bytes, idx, 3)) * 0.01));
            idx += 3;
            meter.setWorkTime(Integer.parseInt(byteToHexStringFlip(bytes, idx, 3)));
            idx += 3;
            meter.setMeterDate(UtilTime.StringToDate(byteToHexStringFlip(bytes, idx, 7), "yyyyMMddHHmmss"));
            idx += 7;
            meter.setMeterStatus(byteToHexString(bytes, idx, 2));
            meters.add(meter);
            idx += 4;
            len -= (idx + 1);
        }
        return meters;
    }

}
